package com.chc.util;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;

public class LogFilter implements Filter {
	private static final Logger logger = LoggerFactory.getLogger(LogFilter.class);
	
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		String ip = request.getRemoteAddr();
		String path = null;
		try {
			MDC.put("remoteIp", ip);
			path = ((HttpServletRequest)request).getRequestURI();
			
			logger.info("start access servlet: " + path);
			chain.doFilter(request, response);
		} finally {
			logger.info("end access servlet: " + path);
			MDC.remove("remoteIp");
		}
	}

	@Override
	public void destroy() {

	}

}
